package controller;

import java.io.IOException;
import java.io.OutputStream;
import java.sql.Connection;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.BookRespository;
import model.NewsRepository;
import myBeans.BookInfo;
import myBeans.NewsInfo;

/**
 * Servlet implementation class BookCoverImageServlet
 */
@WebServlet("/BookCoverImage")
public class BookCoverImageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public BookCoverImageServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String isbn= request.getParameter("isbn");
		
		Connection conn = (Connection) getServletContext().getAttribute("connection");
		
		try {
			BookRespository bookRepo = new BookRespository(conn);
			BookInfo book = bookRepo.GetBookById(isbn);
			
			response.setContentType(book.getCoverImageContentType());
			
			byte[] imgData = book.getBookCoverImage().getBytes(1, (int) book.getBookCoverImage().length());
			
			OutputStream out = response.getOutputStream();
			out.write(imgData);
			out.flush();
			out.close();
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
